
package com.gitee.flow.dao;

import com.gitee.flow.entity.HiTaskinstEntity;
import com.gitee.jmash.core.orm.jpa.BaseDao;
import com.gitee.jmash.core.orm.jpa.SqlBuilder;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jmash.flow.protobuf.HiTaskinstReq;
import org.apache.commons.lang3.StringUtils;

/**
 * HiTaskinst实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class HiTaskinstDao extends BaseDao<HiTaskinstEntity, String> {

  public HiTaskinstDao() {
    super();
  }

  public HiTaskinstDao(TenantEntityManager tem) {
    super(tem);
  }

  /**
   * 查询记录数.
   */
  public Integer findCount(HiTaskinstReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select count(s) ");
    Object obj = this.findSingleResultByParams(query, sqlBuilder.getParams());
    return (obj == null) ? 0 : Integer.valueOf(obj.toString());
  }

  /**
   * 综合查询.
   */
  public List<HiTaskinstEntity> findListByReq(HiTaskinstReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    return this.findListByParams(query, sqlBuilder.getParams());
  }


  /**
   * Create SQL By Req .
   */
  public SqlBuilder createSql(HiTaskinstReq req) {
    StringBuilder sql = new StringBuilder(" from HiTaskinstEntity s where 1=1  ");
    Map<String, Object> params = new HashMap<String, Object>();

    if (StringUtils.isNotBlank(req.getState())) {
      sql.append(" and s.state = :state ");
      params.put("state", req.getState());
    }

    if (StringUtils.isNotBlank(req.getProcInstId())) {
      sql.append(" and s.procInstId = :procInstId ");
      params.put("procInstId", req.getProcInstId());
    }

    String orderSql = "";
    if (StringUtils.isNotBlank(req.getOrderName())) {
      orderSql = String.format(" order by %s %s ", req.getOrderName(),
          req.getOrderAsc() ? " asc " : " desc ");
    }

    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }


}
